package com.itheima.upload.banben4;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class MyRunable implements Runnable {
    private Socket accept;

    public MyRunable(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        //从连接中获取输入流 accept.getInputStream
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        BufferedWriter writer = null;
        try {
            InputStream is = accept.getInputStream();
            //用字节缓冲流读数据
            bis = new BufferedInputStream(is);
            //创建本地字节缓冲输出流写文件
            bos = new BufferedOutputStream(new FileOutputStream("day16\\" + UUID.randomUUID() + ".png"));
            byte[] bytes = new byte[1024];
            int len;
            //循环读写将 上传的文件保存到本地
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);

            }
            //从连接对象中获取输出流(字节)accept.getOutputStream
            OutputStream os = accept.getOutputStream();
            //将字符输出流转换成字节输出流(OutputStreamWriter) writer
            writer = new BufferedWriter(new OutputStreamWriter(os));
            //使用字符流写数据writer.writer()
            writer.write("上传成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
